package com.imooc.springcloud.controller;

import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 顾志杰
 * @date 2021/5/21-11:17
 */
@RestController
@Slf4j
public class Controller {
    /**
     * 限流组件没秒发放两个通行证
     */
    RateLimiter limiter = RateLimiter.create(2.0);


    /**
     * 非阻塞限流
     * count 每秒消耗的令牌数 默认1
     */
    @GetMapping("tryAcquire")
    public String tryAcquire(Integer count){
        if (limiter.tryAcquire(count)){
            log.info("success, rate is {}",limiter.getRate());
            return "scuess";
        }else {
            log.info("fail,rate is {}",limiter.getRate());
            return "fail";
        }
    }


    /**
     * 限定时间非阻塞限流
     * count 每秒消耗的令牌数 默认1
     * timeOut 限定的时间
     * 如果在限定时间内生成的令牌数大于消耗的令牌数则一定会成功
     * 如果在限定时间内生成的令牌数小于消耗的令牌数则会进行限流操作直到生成的令牌数足够一次消耗
     */
    @GetMapping("tryAcquireWithTimeOut")
    public String tryAcquireWithTimeOut(Integer count,Integer timeOut){
        if (limiter.tryAcquire(count,timeOut, TimeUnit.SECONDS)){
            log.info("success, rate is {}",limiter.getRate());
            return "scuess";
        }else {
            log.info("fail,rate is {}",limiter.getRate());
            return "fail";
        }
    }


    /**
     * 同步阻塞限流
     * count 每秒消耗的令牌数 默认1
     */
    @GetMapping("acquire")
    public String acquire(Integer count){
        limiter.acquire(count);
        log.info("success, rate is {}",limiter.getRate());
        return "success";
    }
}
